﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace VTMessenger.ViewModels
{
    public class ViewModel
    {
        private string _userName;
        private string _roomName;

        private HubConnection _connection;
        private IHubProxy _hubProxy;
        public ObservableCollection<string> Messages { get; set; }

        public ViewModel()
        {
            Messages = new ObservableCollection<string>();

            _connection = new HubConnection("http://192.168.1.104:80");
            _hubProxy = _connection.CreateHubProxy("chatHub");

        }

        public async Task Login(string roomName, string userName)
        {
            _roomName = roomName;
            _userName = userName;

            await _connection.Start();
            await _hubProxy.Invoke("JoinRoom", new object[] { _roomName, _userName });

            _hubProxy.Subscribe("UserJoinedMessage").Received += 
                list => App.RootFrame.Dispatcher.BeginInvoke(() => { 
                    Messages.Add(list[0].ToString()+" has joined the chat."); 
                    //MessageBox.Show(list[0].ToString() + " has joined the chat.");
                });

            _hubProxy.Subscribe("ReceiveMessage").Received += 
                list => App.RootFrame.Dispatcher.BeginInvoke(() => { 
                    Messages.Add(list[0].ToString()); 
                });

        }

        public async Task SendMessage(string message)
        {
            await _hubProxy.Invoke("SendMessage",new object[]{_roomName,_userName,message});
        }
    }
}
